package cn.jjxx.shiro.session.mgt.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.shiro.session.Session;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import cn.jjxx.shiro.session.RedisUtil;
import cn.jjxx.shiro.session.mgt.ShiroSessionRepository;



/**
 * 实现session操作
 *@Title JedisShiroSessionRepository.java
 *@description TODO
 *@time 2020年6月18日 上午11:32:14
 *@author YAOXIONG
 *@version 1.0
 *
 */
@Component
public class JedisShiroSessionRepository implements ShiroSessionRepository{

	
	@Resource
	private RedisTemplate<Object,Object> redisTemplate; 
	

	public RedisTemplate<Object, Object> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@Override
	public void saveSession(Session session) {
		Long timeOut = session.getTimeout() / 1000;  
		String key = RedisUtil.REDIS_SHIRO_SESSION+":"+session.getId();
		redisTemplate.opsForValue().set(key,session,timeOut, TimeUnit.SECONDS);
	}

	@Override
	public void deleteSession(Serializable sessionId) {
		// TODO Auto-generated method stub
		if (sessionId != null) {
			redisTemplate.delete(sessionId);
		}
	}

	@Override
	public Session getSession(Serializable sessionId) {
		Session session = null;
		if (sessionId != null) {
			String key = RedisUtil.REDIS_SHIRO_SESSION+"-"+sessionId;
			session = (Session)redisTemplate.opsForValue().get(key);
		}
		return session;
	}

	@Override
	public Collection<Session> getAllSessions() {
		Set<Session> sessions = new HashSet<Session>();  
		Set<Object> Keys =  redisTemplate.keys(RedisUtil.REDIS_SHIRO_SESSION+"*");
		for (Object key : Keys) {
			Session session = (Session)redisTemplate.opsForValue().get(key);
			sessions.add(session);
		}
		return sessions;
	} 
}